package com.yyk.yykywd.mvvm.ui

import android.content.Context
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener
import com.yyk.yykywd.*
import com.yyk.yykywd.base.BaseActivity
import com.yyk.yykywd.mvvm.adapter.PotentialCustomerAdapter
import com.yyk.yykywd.mvvm.entity.PotentialCustomerBean
import com.yyk.yykywd.mvvm.entity.Screen
import com.yyk.yykywd.mvvm.view_model.PotentialCustomerViewModel
import com.yyk.yykywd.util.ToAnotherActivity
import kotlinx.android.synthetic.main.activity_potential_customer.*
import kotlinx.android.synthetic.main.layout_load.*
import razerdp.basepopup.BasePopupWindow

class PotentialCustomerActivity : BaseActivity() {
    private lateinit var viewModel: PotentialCustomerViewModel
    private lateinit var potentialCustomerAdapter: PotentialCustomerAdapter
    private lateinit var popup1: ScreenPopup
    private lateinit var popup2: ScreenPopup
    private lateinit var type: List<Screen>
    private lateinit var scope: List<Screen>

    private var customerType =  0
    private var customerScope = 1
    override fun initView() {

        viewModel = ViewModelProviders.of(this).get(PotentialCustomerViewModel::class.java)
        viewModel.type = intent.getStringExtra(TYPE)

        setBackArrow()
        when (viewModel.type) {
            POTENTIAL_CUSTOMER -> {
                setTitle("意向客户")
                cl_search.visibility = View.VISIBLE
                cl_type.visibility = View.VISIBLE
                cl_scope.visibility = View.VISIBLE
            }
            C_CUSTOMER -> {
                setTitle("C类客户")
                cl_search.visibility = View.GONE
                cl_type.visibility = View.GONE
                cl_scope.visibility = View.GONE
            }
            SIGN_CONTRACT -> {
                setTitle("签订合同")
                cl_search.visibility = View.VISIBLE
                cl_type.visibility = View.VISIBLE
                cl_scope.visibility = View.VISIBLE
            }
        }

        potentialCustomerAdapter = PotentialCustomerAdapter(mActivity, viewModel.type, R.layout.item_potential_customer, viewModel.potentials)
        //调用同一个对象的多个方法 / 属性时，可以省去对象名重复，直接调用方法名 / 属性即可
        with(rv) {
            layoutManager = LinearLayoutManager(mActivity)
            adapter = potentialCustomerAdapter
        }

        val screen = Screen("全部客户", true,0)
        val screen1 = Screen("代理商客户", false,2)
        val screen2 = Screen("医院客户", false,1)
        val screen5 = Screen("全部客户", true,1)
        if (getLevel() != "普通员工") {
            val screen3 = Screen("只看自己", false,2)
            val screen4 = Screen("查看下属", false,3)
            scope = listOf(screen5, screen3, screen4)
        } else {
            scope = listOf(screen5)
        }
        type = listOf(screen, screen1, screen2)
        popup1 = ScreenPopup(mActivity, type, CUSTOMER_TYPE)
        popup2 = ScreenPopup(mActivity, scope, CUSTOMER_SCOPE)
    }

    override fun initData() {
        loading_layout.showLoading()
    }

    override fun onResume() {
        super.onResume()
        reloadData()
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_potential_customer
    }

    override fun setListener() {
        super.setListener()

        srl.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                with(viewModel) {
                    loadMore()
                    getList(customerType,customerScope)
                }
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                reloadData()
            }
        })

        viewModel.potentialCustomers.observe(this, Observer<PotentialCustomerBean> {
            hideRefreshAndLoadMore(srl)
            showStateLayout(potentialCustomerAdapter, it.code, viewModel.potentials, it.msg, loading_layout)
        })

        potentialCustomerAdapter.setOnItemClickListener { _, _, position ->
            with(viewModel.potentials[position]) {
                when (viewModel.type) {
                    POTENTIAL_CUSTOMER -> {
                        if (client_type == 1) {
                            ToAnotherActivity.toReturnMoneyDetailActivity(mActivity, FROM_POTENTIAL_CUSTOMER_HOSPITAL,
                                    id.toString(), flag, show_type, 0)
                        } else {
                            ToAnotherActivity.toReturnMoneyDetailActivity(mActivity, FROM_POTENTIAL_CUSTOMER_AGENT,
                                    id.toString(), flag, show_type, 0)
                        }
                    }
                    SIGN_CONTRACT -> {
                        if (client_type == 1) {
                            ToAnotherActivity.toReturnMoneyDetailActivity(mActivity, FROM_SIGN_CONTRACT_HOSPITAL,
                                    id.toString(), flag, show_type, type_s)
                        } else {
                            ToAnotherActivity.toDetailActivity(mActivity,
                                    FROM_SIGN_CONTRACT_AGENT,
                                    id.toString(),show_type)
                        }
                    }
                    C_CUSTOMER -> {
                        if (client_type == 1) {
                            ToAnotherActivity.toReturnMoneyDetailActivity(mActivity, FROM_C_CUSTOMER_HOSPITAL,
                                    id.toString(), flag, show_type, 0)
                        } else {
                            ToAnotherActivity.toReturnMoneyDetailActivity(mActivity, FROM_C_CUSTOMER_AGENT,
                                    id.toString(), flag, show_type, 0)
                        }
                    }
                }
            }
        }

        cl_search.setOnClickListener {
            ToAnotherActivity.toSearchCustomerActivity(mActivity, viewModel.type)
        }

        cl_type.setOnClickListener {
            popup1.setAlignBackground(true)
            popup1.setAlignBackgroundGravity(Gravity.TOP)
            popup1.showPopupWindow(it)

            tv_type.setTextColor(ContextCompat.getColor(mActivity, R.color.col_5987ff))
            iv1.setImageResource(R.drawable.icon_sq)
        }
        cl_scope.setOnClickListener {
            popup2.setAlignBackground(true)
            popup2.setAlignBackgroundGravity(Gravity.TOP)
            popup2.showPopupWindow(it)

            tv_scope.setTextColor(ContextCompat.getColor(mActivity, R.color.col_5987ff))
            iv2.setImageResource(R.drawable.icon_sq)
        }

        popup1.onDismissListener = object : BasePopupWindow.OnDismissListener() {
            override fun onDismiss() {
                tv_type.setTextColor(ContextCompat.getColor(mActivity, R.color.black_33))
                iv1.setImageResource(R.drawable.icon_zk)
            }
        }

        popup2.onDismissListener = object : BasePopupWindow.OnDismissListener() {
            override fun onDismiss() {
                tv_scope.setTextColor(ContextCompat.getColor(mActivity, R.color.black_33))
                iv2.setImageResource(R.drawable.icon_zk)
            }
        }
    }

    private fun reloadData() {
        with(viewModel) {
            refresh(potentials)
            getList(customerType,customerScope)
        }
    }

    fun getSelectedType(position: Int) {
        popup1.dismiss()
        tv_type.text = type[position].type
        customerType = type[position].flag
        reloadData()
    }

    fun getSelectedScope(position: Int) {
        popup2.dismiss()
        tv_scope.text = scope[position].type
        customerScope = scope[position].flag
        reloadData()
    }
}

const val CUSTOMER_TYPE = "客户类型"
const val CUSTOMER_SCOPE = "客户范围"

class ScreenPopup(context: Context, list: List<Screen>, type: String) : BasePopupWindow(context) {

    init {
        val rv = findViewById<RecyclerView>(R.id.rv)
        val screenAdapter = ScreenAdapter(context, R.layout.item_screen, list)
        rv.adapter = screenAdapter

        screenAdapter.setOnItemClickListener { _, _, position ->
            for (screen in list) {
                screen.isSelected = false
            }
            list[position].isSelected = true
            screenAdapter.notifyDataSetChanged()
            if (type == CUSTOMER_TYPE) {
                (context as PotentialCustomerActivity).getSelectedType(position)
            } else {
                (context as PotentialCustomerActivity).getSelectedScope(position)
            }
        }
    }

    override fun onCreateContentView(): View {
        return createPopupById(R.layout.popup_screen)
    }
}

class ScreenAdapter(private val context: Context,
                    layoutResId: Int,
                    data: List<Screen>)
    : BaseQuickAdapter<Screen, BaseViewHolder>(layoutResId, data) {
    override fun convert(helper: BaseViewHolder, item: Screen) {
        val rl = helper.getView<RelativeLayout>(R.id.rl)
        val iv = helper.getView<ImageView>(R.id.iv)
        val tvType = helper.getView<TextView>(R.id.tv_type)
        tvType.text = item.type

        if (item.isSelected) {
            iv.visibility = View.VISIBLE
            rl.setBackgroundResource(R.color.col_1a7299fe)
            tvType.setTextColor(ContextCompat.getColor(context, R.color.col_5987ff))
        } else {
            iv.visibility = View.GONE
            rl.setBackgroundResource(R.color.white)
            tvType.setTextColor(ContextCompat.getColor(context, R.color.col_80))
        }
    }
}
